// wii libraries
#include <grrlib.h>

// custom libraries
#include "..\..\include\graphics\image.h" // matching header


// ==================================
//    CONSTRUCTORS and DESTRUCTORS
// ==================================

Image::Image()
{
	data_ = 0;
}

Image::Image(const char* buffer, unsigned int size)
{
	data_ = 0;
	load(buffer, size);
}

Image::~Image()
{
	if (data_ != 0)
		clear();
}


// ==================================
//          LOAD and CLEAR
// ==================================

void Image::load(const char* buffer, unsigned int size)
{
	if (data_ == 0) {
		if (buffer != 0) {
			GRRLIB_texImg* tex = 0;

			bool isJpg = (buffer[0] == 0xFF) && (buffer[1] == 0xD8) &&
				         (buffer[2] == 0xFF);
			bool isBmp = (buffer[0] == 'B') && (buffer[1] == 'M');
			bool isPng = !(isJpg || isBmp); // Better way to detect?

			if (isJpg)
				tex = GRRLIB_LoadTextureJPGEx((u8*)buffer, size);
			else if (isBmp)
				tex = GRRLIB_LoadTextureBMP((u8*)buffer);
			else if (isPng)
				tex = GRRLIB_LoadTexturePNG((u8*)buffer);

			data_   = (void*)tex;
		}
	}
}

void Image::clear()
{
	if (data_ != 0) {
		GRRLIB_FreeTexture((GRRLIB_texImg*)data_);
		data_ = 0;
	}
}


// ==================================
//             GETTERS
// ==================================

void* Image::getData()
{
    return data_;
}